import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/providers/app_providers.dart';
import '../../core/types/app_types.dart';

/**
 * 设置面板组件
 * 提供应用设置和配置选项
 */
class SettingsPanel extends ConsumerWidget {
  const SettingsPanel({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Container(
      width: 320,
      height: double.infinity,
      decoration: BoxDecoration(
        color: Theme.of(context).scaffoldBackgroundColor,
        border: Border(
          left: BorderSide(
            color: Theme.of(context).dividerColor,
          ),
        ),
      ),
      child: Column(
        children: [
          // 标题栏
          _buildHeader(context, ref),
          
          // 设置内容
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildAccountSection(context, ref),
                  const SizedBox(height: 24),
                  _buildSyncSection(context, ref),
                  const SizedBox(height: 24),
                  _buildAppearanceSection(context, ref),
                  const SizedBox(height: 24),
                  _buildDataSection(context, ref),
                  const SizedBox(height: 24),
                  _buildAboutSection(context, ref),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /**
   * 构建标题栏
   */
  Widget _buildHeader(BuildContext context, WidgetRef ref) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: Theme.of(context).dividerColor,
          ),
        ),
      ),
      child: Row(
        children: [
          const Icon(Icons.settings),
          const SizedBox(width: 8),
          const Text(
            '设置',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
            ),
          ),
          const Spacer(),
          IconButton(
            onPressed: () {
              ref.read(showSettingsProvider.notifier).setShowSettings(false);
            },
            icon: const Icon(Icons.close),
            tooltip: '关闭',
          ),
        ],
      ),
    );
  }

  /**
   * 构建账户设置部分
   */
  Widget _buildAccountSection(BuildContext context, WidgetRef ref) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('账户'),
        const SizedBox(height: 12),
        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                Row(
                  children: [
                    CircleAvatar(
                      radius: 24,
                      backgroundColor: Theme.of(context).primaryColor,
                      child: const Icon(
                        Icons.person,
                        color: Colors.white,
                      ),
                    ),
                    const SizedBox(width: 12),
                    const Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '未登录',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          Text(
                            '登录以同步您的笔记',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                Row(
                  children: [
                    Expanded(
                      child: OutlinedButton(
                        onPressed: () {
                          // TODO: 实现登录功能
                        },
                        child: const Text('登录'),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () {
                          // TODO: 实现注册功能
                        },
                        child: const Text('注册'),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /**
   * 构建同步设置部分
   */
  Widget _buildSyncSection(BuildContext context, WidgetRef ref) {
    final syncStatus = ref.watch(syncStatusNotifierProvider);
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('同步'),
        const SizedBox(height: 12),
        Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                Row(
                  children: [
                    Icon(
                      _getSyncIcon(syncStatus.status),
                      color: _getSyncColor(syncStatus.status),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            _getSyncStatusText(syncStatus.status),
                            style: const TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          if (syncStatus.message != null)
                            Text(
                              syncStatus.message!,
                              style: const TextStyle(
                                fontSize: 12,
                                color: Colors.grey,
                              ),
                            ),
                        ],
                      ),
                    ),
                    if (syncStatus.status != SyncStatus.syncing)
                      TextButton(
                        onPressed: () {
                          // TODO: 实现手动同步
                        },
                        child: const Text('同步'),
                      ),
                  ],
                ),
                if (syncStatus.progress != null && syncStatus.progress! > 0) ...[
                  const SizedBox(height: 12),
                  LinearProgressIndicator(
                    value: syncStatus.progress,
                  ),
                ],
              ],
            ),
          ),
        ),
        const SizedBox(height: 12),
        SwitchListTile(
          title: const Text('自动同步'),
          subtitle: const Text('在网络可用时自动同步数据'),
          value: true, // TODO: 从设置中读取
          onChanged: (value) {
            // TODO: 保存设置
          },
        ),
      ],
    );
  }

  /**
   * 构建外观设置部分
   */
  Widget _buildAppearanceSection(BuildContext context, WidgetRef ref) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('外观'),
        const SizedBox(height: 12),
        Card(
          child: Column(
            children: [
              ListTile(
                leading: const Icon(Icons.palette_outlined),
                title: const Text('主题'),
                subtitle: const Text('浅色'),
                trailing: const Icon(Icons.chevron_right),
                onTap: () {
                  _showThemeDialog(context);
                },
              ),
              const Divider(height: 1),
              ListTile(
                leading: const Icon(Icons.text_fields),
                title: const Text('字体大小'),
                subtitle: const Text('中等'),
                trailing: const Icon(Icons.chevron_right),
                onTap: () {
                  _showFontSizeDialog(context);
                },
              ),
              const Divider(height: 1),
              SwitchListTile(
                secondary: const Icon(Icons.format_line_spacing),
                title: const Text('紧凑模式'),
                subtitle: const Text('减少界面元素间距'),
                value: false, // TODO: 从设置中读取
                onChanged: (value) {
                  // TODO: 保存设置
                },
              ),
            ],
          ),
        ),
      ],
    );
  }

  /**
   * 构建数据设置部分
   */
  Widget _buildDataSection(BuildContext context, WidgetRef ref) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('数据'),
        const SizedBox(height: 12),
        Card(
          child: Column(
            children: [
              ListTile(
                leading: const Icon(Icons.backup_outlined),
                title: const Text('导出数据'),
                subtitle: const Text('将笔记导出为文件'),
                trailing: const Icon(Icons.chevron_right),
                onTap: () {
                  // TODO: 实现数据导出
                },
              ),
              const Divider(height: 1),
              ListTile(
                leading: const Icon(Icons.restore_outlined),
                title: const Text('导入数据'),
                subtitle: const Text('从文件导入笔记'),
                trailing: const Icon(Icons.chevron_right),
                onTap: () {
                  // TODO: 实现数据导入
                },
              ),
              const Divider(height: 1),
              ListTile(
                leading: Icon(
                  Icons.delete_outline,
                  color: Colors.red.shade600,
                ),
                title: Text(
                  '清空数据',
                  style: TextStyle(
                    color: Colors.red.shade600,
                  ),
                ),
                subtitle: const Text('删除所有本地数据'),
                trailing: const Icon(Icons.chevron_right),
                onTap: () {
                  _showClearDataDialog(context, ref);
                },
              ),
            ],
          ),
        ),
      ],
    );
  }

  /**
   * 构建关于部分
   */
  Widget _buildAboutSection(BuildContext context, WidgetRef ref) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionTitle('关于'),
        const SizedBox(height: 12),
        Card(
          child: Column(
            children: [
              ListTile(
                leading: const Icon(Icons.info_outline),
                title: const Text('版本'),
                subtitle: const Text('1.0.0'),
                trailing: const Icon(Icons.chevron_right),
                onTap: () {
                  // TODO: 显示版本信息
                },
              ),
              const Divider(height: 1),
              ListTile(
                leading: const Icon(Icons.help_outline),
                title: const Text('帮助'),
                trailing: const Icon(Icons.chevron_right),
                onTap: () {
                  // TODO: 显示帮助信息
                },
              ),
              const Divider(height: 1),
              ListTile(
                leading: const Icon(Icons.feedback_outlined),
                title: const Text('反馈'),
                trailing: const Icon(Icons.chevron_right),
                onTap: () {
                  // TODO: 打开反馈页面
                },
              ),
            ],
          ),
        ),
      ],
    );
  }

  /**
   * 构建节标题
   */
  Widget _buildSectionTitle(String title) {
    return Text(
      title,
      style: const TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.w600,
      ),
    );
  }

  /**
   * 获取同步状态图标
   */
  IconData _getSyncIcon(SyncStatus status) {
    switch (status) {
      case SyncStatus.synced:
        return Icons.cloud_done_outlined;
      case SyncStatus.syncing:
        return Icons.sync;
      case SyncStatus.pending:
        return Icons.cloud_upload_outlined;
      case SyncStatus.error:
        return Icons.error_outline;
      case SyncStatus.local:
        return Icons.cloud_off_outlined;
    }
  }

  /**
   * 获取同步状态颜色
   */
  Color _getSyncColor(SyncStatus status) {
    switch (status) {
      case SyncStatus.synced:
        return Colors.green;
      case SyncStatus.syncing:
        return Colors.blue;
      case SyncStatus.pending:
        return Colors.orange;
      case SyncStatus.error:
        return Colors.red;
      case SyncStatus.local:
        return Colors.grey;
    }
  }

  /**
   * 获取同步状态文本
   */
  String _getSyncStatusText(SyncStatus status) {
    switch (status) {
      case SyncStatus.synced:
        return '已同步';
      case SyncStatus.syncing:
        return '同步中';
      case SyncStatus.pending:
        return '待同步';
      case SyncStatus.error:
        return '同步失败';
      case SyncStatus.local:
        return '离线模式';
    }
  }

  /**
   * 显示主题选择对话框
   */
  void _showThemeDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择主题'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            RadioListTile<String>(
              title: const Text('浅色'),
              value: 'light',
              groupValue: 'light', // TODO: 从设置中读取
              onChanged: (value) {
                // TODO: 保存设置
                Navigator.of(context).pop();
              },
            ),
            RadioListTile<String>(
              title: const Text('深色'),
              value: 'dark',
              groupValue: 'light', // TODO: 从设置中读取
              onChanged: (value) {
                // TODO: 保存设置
                Navigator.of(context).pop();
              },
            ),
            RadioListTile<String>(
              title: const Text('跟随系统'),
              value: 'system',
              groupValue: 'light', // TODO: 从设置中读取
              onChanged: (value) {
                // TODO: 保存设置
                Navigator.of(context).pop();
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  /**
   * 显示字体大小选择对话框
   */
  void _showFontSizeDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择字体大小'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            RadioListTile<String>(
              title: const Text('小'),
              value: 'small',
              groupValue: 'medium', // TODO: 从设置中读取
              onChanged: (value) {
                // TODO: 保存设置
                Navigator.of(context).pop();
              },
            ),
            RadioListTile<String>(
              title: const Text('中等'),
              value: 'medium',
              groupValue: 'medium', // TODO: 从设置中读取
              onChanged: (value) {
                // TODO: 保存设置
                Navigator.of(context).pop();
              },
            ),
            RadioListTile<String>(
              title: const Text('大'),
              value: 'large',
              groupValue: 'medium', // TODO: 从设置中读取
              onChanged: (value) {
                // TODO: 保存设置
                Navigator.of(context).pop();
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  /**
   * 显示清空数据确认对话框
   */
  void _showClearDataDialog(BuildContext context, WidgetRef ref) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('清空数据'),
        content: const Text('确定要删除所有本地数据吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              try {
                // TODO: 实现清空数据功能
                Navigator.of(context).pop();
                
                ref.read(notificationNotifierProvider.notifier).showSuccess(
                  message: '数据已清空',
                );
              } catch (e) {
                ref.read(notificationNotifierProvider.notifier).showError(
                  message: '清空数据失败: $e',
                );
              }
            },
            child: Text(
              '确定',
              style: TextStyle(color: Colors.red.shade600),
            ),
          ),
        ],
      ),
    );
  }
}